package com.ayoka.mvp;

import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.ayoka.base.BasePresenter;
import com.ayoka.base.IBaseView;
import com.ayoka.mvp.CustomerServiceMVP.CustomerServiceModel.MessageOptionBean;
import com.ayoka.Constant;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jcp.baselibrary.utils.SPUtil;
import com.tencent.TIMCallBack;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMCustomElem;
import com.tencent.TIMElem;
import com.tencent.TIMElemType;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageDraft;
import com.tencent.TIMMessageLocator;
import com.tencent.TIMValueCallBack;
import com.tencent.timsdk.event.MessageEvent;
import com.tencent.timsdk.event.RefreshEvent;
import com.tencent.timsdk.interf.ChatView;
import com.tencent.timsdk.model.TextMessage;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by gabriel on 2017/3/5.
 */

public interface CustomerServiceMVP {

    interface CustomerServiceModel {

        class MessageOptionBean {
            public String text;
            public String value;
        }
    }

    interface ICustomerServiceView extends IBaseView{

        void showMessageOptions(List<MessageOptionBean> options);
    }


    class CustomerServicePresenter extends BasePresenter<ICustomerServiceView> implements Observer {

        private ChatView view;
        private TIMConversation conversation;
        private boolean isGettingMessage = false;
        private final int LAST_MESSAGE_NUM = 20;

        public CustomerServicePresenter(ChatView view, String identify, TIMConversationType type) {
            this.view = view;
            conversation = TIMManager.getInstance().getConversation(type, identify);
        }


        /**
         * 加载页面逻辑
         */
        public void start() {
            //注册消息监听
            MessageEvent.getInstance().addObserver(this);
            RefreshEvent.getInstance().addObserver(this);
            getMessage(null);
            if (conversation.hasDraft()) {
                view.showDraft(conversation.getDraft());
            }
            long messageNum = conversation.getUnreadMessageNum();
            // 半小时内推出不发送消息
            long lastQuitMills = SPUtil.getLong(Constant.QUIT_AI_MILLS, System.currentTimeMillis());
            if (System.currentTimeMillis() - lastQuitMills > 30 * 60 * 1000) {
                sendOnlineMessage(new TextMessage("888").getMessage());
            }
        }


        /**
         * 中止页面逻辑
         */
        public void stop() {
            //注销消息监听
            MessageEvent.getInstance().deleteObserver(this);
            RefreshEvent.getInstance().deleteObserver(this);
        }

        /**
         * 获取聊天TIM会话
         */
        public TIMConversation getConversation() {
            return conversation;
        }

        /**
         * 发送消息
         *
         * @param message 发送的消息
         */
        public void sendMessage(final TIMMessage message) {
            conversation.sendMessage(message, new TIMValueCallBack<TIMMessage>() {
                @Override
                public void onError(int code, String desc) {//发送消息失败
                    //错误码code和错误描述desc，可用于定位请求失败原因
                    //错误码code含义请参见错误码表
                    view.onSendMessageFail(code, desc, message);
                }

                @Override
                public void onSuccess(TIMMessage msg) {
                    //发送消息成功,消息状态已在sdk中修改，此时只需更新界面
                    MessageEvent.getInstance().onNewMessage(null);

                }
            });
            //message对象为发送中状态
            MessageEvent.getInstance().onNewMessage(message);
        }


        /**
         * 发送在线消息
         *
         * @param message 发送的消息
         */
        public void sendOnlineMessage(final TIMMessage message) {
            conversation.sendOnlineMessage(message, new TIMValueCallBack<TIMMessage>() {
                @Override
                public void onError(int i, String s) {
                    view.onSendMessageFail(i, s, message);
                }

                @Override
                public void onSuccess(TIMMessage message) {

                }
            });
        }


        /**
         * This method is called if the specified {@code Observable} object's
         * {@code notifyObservers} method is called (because the {@code Observable}
         * object has been updated.
         *
         * @param observable the {@link Observable} object.
         * @param data       the data passed to {@link Observable#notifyObservers(Object)}.
         */
        @Override
        public void update(Observable observable, Object data) {
            if (observable instanceof MessageEvent) {
                if (data instanceof TIMMessage || data == null) {
                    TIMMessage message = (TIMMessage) data;
                    if (message == null || message.getConversation().getPeer().equals(conversation.getPeer()) && message.getConversation().getType() == conversation.getType()) {
                        view.showMessage(message);
                        //当前聊天界面已读上报，用于多终端登录时未读消息数同步
                        readMessages();
                    }
                    if (message == null) return;
                    for (int i = 0; i < message.getElementCount(); i++) {
                        TIMElem timElem = message.getElement(i);
                        if (timElem.getType() == TIMElemType.Custom) {
                            TIMCustomElem customElem = (TIMCustomElem) timElem;
                            String optionData = new String(customElem.getData());
                            if (TextUtils.isEmpty(optionData)) return;
                            Log.d("TAG", optionData);
                            if (optionData.startsWith("[")) {
                                try {
                                    Type type = new TypeToken<List<CustomerServiceModel.MessageOptionBean>>() {}.getType();
                                    List<CustomerServiceModel.MessageOptionBean> options = new Gson().fromJson(optionData, type);
                                    mViewRef.get().showMessageOptions(options);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                } else if (data instanceof TIMMessageLocator) {
                    TIMMessageLocator msg = (TIMMessageLocator) data;
                    view.showRevokeMessage(msg);
                }

            } else if (observable instanceof RefreshEvent) {
                view.clearAllMessage();
                getMessage(null);
            }
        }


        /**
         * 获取消息
         *
         * @param message 最后一条消息
         */
        public void getMessage(@Nullable TIMMessage message) {
            if (!isGettingMessage) {
                isGettingMessage = true;
                conversation.getMessage(LAST_MESSAGE_NUM, message, new TIMValueCallBack<List<TIMMessage>>() {
                    @Override
                    public void onError(int i, String s) {
                        isGettingMessage = false;
                        Log.e(TAG, "message error" + s);
                    }

                    @Override
                    public void onSuccess(List<TIMMessage> timMessages) {
                        isGettingMessage = false;
                        view.showMessage(timMessages);
                    }
                });
            }

        }

        /**
         * 设置会话为已读
         */
        public void readMessages() {
            conversation.setReadMessage();
        }


        /**
         * 保存草稿
         *
         * @param message 消息数据
         */
        public void saveDraft(TIMMessage message) {
            conversation.setDraft(null);
            if (message != null && message.getElementCount() > 0) {
                TIMMessageDraft draft = new TIMMessageDraft();
                for (int i = 0; i < message.getElementCount(); ++i) {
                    draft.addElem(message.getElement(i));
                }
                conversation.setDraft(draft);
            }

        }
    }

}
